package com.lyz.file.impl;

import java.io.File;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.lyz.config.ConfigFactory;
import com.lyz.config.IConfig;
import com.lyz.file.IFileFetcher;
import com.lyz.file.IFileProcess;
import com.lyz.file.IFileQueue;
import com.lyz.util.PropertiesUtil;
import com.lyz.util.SleepUtil;

public class LogFileFetcher4FixName implements IFileFetcher{

	private final static Logger logger = Logger.getLogger(LogFileFetcher4FixName.class);

	private IFileQueue queue = null;

	private IConfig config = null;
	
	private long fetchInterval = 0;
	
	private long firstFetchTime = 0;
	
	private Timer timer = null;
	
	private String tag = null;
	
	/**
	 * 该方法需要在实例化之后立即调用
	 * @param queue
	 * @param tag
	 */
	public IFileFetcher initFetcher(IFileQueue queue, IFileProcess proc, String tag){
		this.queue = queue;
		this.tag = tag;

		config = ConfigFactory.getConfig();
		fetchInterval = config.getFileFetcherInterval(tag);
		firstFetchTime = config.getFileFirstFetcherTime(tag);
		timer = new Timer();
		
		return this;
	}

	public void start() {
		/*添加一个定时执行程序，在固定时刻获取文件*/
		timer.scheduleAtFixedRate(new TimerTask() {
			long firstTime = firstFetchTime;
			long interval = fetchInterval;
			/*需要忽略的执行次数*/
			long times = System.currentTimeMillis()-firstTime>0?(System.currentTimeMillis()-firstTime)/interval+1:0;
			
			@Override
			public void run() {
				/*忽略错过的执行次数*/
				if(times>0){
					logger.info("ignore for one time...");
					times--;
					return;
				}
				logger.info("try to fetch new file...");
				getNewFile();
				
			}
		}, new Date(firstFetchTime), fetchInterval);
	}

	public void getNewFile() {

		File file = null;
		
		String newFileName = config.getFileName(tag);
		/*确保每一次定时执行，都能够加入队列一个文件*/
		do{
			file = new File(config.getLogDirectory(tag) + "/" + newFileName);
			if(!file.exists()){
				SleepUtil.sleepForCertainTime(5000);
			}			
		}while(!file.exists());
		
		// 文件存在,则将其加入队列
		queue.addFile(newFileName);
		logger.info("add " + newFileName + " to the queue..."
				+ queue.size() + " files in queue!");

	}
	
	public String createFileName(){
		return config.getFileName(tag);
	}
	
	public void initFileQueue(){
		File file = new File(config.getLogDirectory(tag)+"/"+config.getFileName(tag));
		if(file.exists()){
			queue.addFile(config.getFileName(tag));
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
